package com.example.demo.excepiton;

import com.example.demo.common.R;
import com.example.demo.utils.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 
 * @author hecheng
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{

    /*
    *  顶级异常
    * */
    @ExceptionHandler(Exception.class)
    public R globalExceptionHandler(Exception e) {

        return R.fail("服务器繁忙");
    }



    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public R customException(CustomException e)
    {

        if (StringUtils.isNull(e.getCode()))
        {
            return R.fail(e.getLocalizedMessage());
        }
        return R.fail(e.getCode(),e.getLocalizedMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public R validatedBindException(BindException e)
    {
        return R.fail(e.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R validExceptionHandler(MethodArgumentNotValidException e)
    {

        return R.fail(e.getBindingResult().getFieldError().getDefaultMessage());
    }



}
